import React, { Component, PropTypes } from 'react';
import SVGInjector from './svg-injector';
import $ from "jquery";
var ReactSVG=React.createClass({ 
  getInitialState:function(){
    return {svg:null}
  },
  getDefaultProps:function(){
    return {
      evalScripts: 'never',
      callback: () => {}
    };
  },
  propTypes:{
    path: PropTypes.string.isRequired,
    className: PropTypes.string,
    evalScripts: PropTypes.oneOf(['always', 'once', 'never']),
    fallbackPath: PropTypes.string,
    callback: PropTypes.func,
    fill:PropTypes.string
  },
  render:function() {

    const {
      className,
      path,
      fallbackPath
    } = this.props;
    let iconHtml = '';
    if (path && path.indexOf('/png')>0) {
      iconHtml = (<img
                      className={className}
                      src={path}
                    />);
      
    } else {
      iconHtml = (<img
                  className={className}
                  data-src={path}
                  data-fallback={fallbackPath}
                  ref={(img) => this._img = img}
                />);
    }
    return iconHtml;

  }, 
  componentDidMount:function() {
    var me=this;
    const {
      evalScripts,
      callback: each,
      fill
    } = this.props;
    if (this.props.path && this.props.path.indexOf('/png')<0) {
      SVGInjector(this._img, {
        evalScripts,
        each,
        rsvg:this,
        fill:fill,
        onLoad:function (svg) { 
          me.svg=svg; 
        }
      });
    }
  },
  componentWillReceiveProps:function(p){ 
    $(this.svg).find("g").attr("fill",p.fill);
    $(this.svg).find("path").attr("fill",p.fill);
  }
});
module.exports=ReactSVG;
